﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace SampleIoc
{
    internal sealed class SampleIocServiceProvider : ISampleIocServiceProvider
    {
        /// <summary>
        /// 
        /// </summary>
        private readonly ServiceProviderEngine _engine;

        private readonly IList<ServiceInfo> _serviceInfos;

        /// <summary>
        /// 
        /// </summary>
        /// <param name="root"></param>
        /// <param name="serviceInfos"></param>
        /// <param name="isRoot">是否为根节点创建的</param>
        internal SampleIocServiceProvider(ServiceProviderEngine root, IList<ServiceInfo> serviceInfos, bool isRoot = false)
        {
            _serviceInfos = serviceInfos;
            if (isRoot)
            {
                _engine = new ServiceProviderEngine(default, root.EngineScope);
            }
            else
            {
                var scope = new ServiceProviderEngineScope(serviceInfos);
                _engine = new ServiceProviderEngine(root.EngineScope, scope);
            }
        }
        /// <summary>
        /// 获取服务 
        /// </summary>
        /// <param name="serviceType"></param>
        /// <returns></returns>
        public object GetService(Type serviceType)
        {
            return _engine.GetService(serviceType);
        }

        /// <summary>
        /// 创建一个新的作用域
        /// </summary>
        /// <returns></returns>
        public ISampleIocServiceProvider CreateScope()
        {
            return new SampleIocServiceProvider(this._engine, this._serviceInfos);
        }

        public void Dispose()
        {
            _engine?.Dispose();
        }
    }
}
